package com.hframe.type;


import com.hframe.typefilter.FilterRef;
import org.apache.log4j.Logger;

public class TFilter<T> {
    private static Logger log = Logger.getLogger(TFilter.class);

    public enum ReadWait {
        NotReadWait, OnlyRead, OnlyWait, ReadWait, ReadNull,
    }

    protected TFilter next = null;
    protected com.hframe.type.T<T> parent = null;
    protected ReadWait readWait = ReadWait.ReadWait;
    protected FilterRef<Object, T> getCall = null;
    protected FilterRef<T, Object> setCall = null;
    protected String name = null;

    public String getName() {
        return name;
    }

    public TFilter<T> setName(String name) {
        this.name = name;
        return this;
    }

    public ReadWait getReadWait() {
        return readWait;
    }

    public TFilter<T> setReadWait(ReadWait readWait) {
        this.readWait = readWait;
        return this;
    }

    public TFilter<T> setGetCall(FilterRef<Object, T> getCall) {
        this.getCall = getCall;
        return this;
    }

    public void setSetCall(FilterRef<T, Object> setCall) {
        this.setCall = setCall;
    }

    public Object get() throws Exception {
        if (null != getCall) {
            return getCall.filter(parent.object);
        }
        return parent.object;
    }

    public void set(Object object) throws Exception {
        if (null != setCall) {
            parent.object = setCall.filter(object);
            return;
        }
        parent.object = (T) object;
    }

    protected static TFilter find(com.hframe.type.T type, Class<? extends TFilter> filterkey) {
        TFilter filter = type.filter;
        while (null != filter) {
            if (filter.getClass().equals(filterkey))
                return filter;
            filter = filter.next;
        }
        return null;
    }

    protected static TFilter getNext(com.hframe.type.T type, Class<? extends TFilter> filterkey) {
        TFilter temp = type.filter;
        while (null != temp) {
            if (temp.getClass().equals(filterkey))
                return temp;
            temp = temp.next;
        }
        try {
            temp = filterkey.newInstance();

        } catch (Exception e) {
            log.error(e, e);
        }
        temp.next = type.filter;
        type.filter = temp;
        return temp;
    }


}
